<template>
  <div style="display:inline-block">
    <span
      v-if="score || showEmpty"
      class="star-icon"
      v-for="(item, index) in starCls"
      :key="index"
      :class="item"
    ></span>
    <span v-if="!score" :style="starStyle">暂无评分</span>
    <span v-if="score&&showScoreNum">{{showScore}}</span>
  </div>
</template>

<script>
export default {
  name: 'star',
  props: {
    score: {
      type: Number,
      default: 0
    },
    showScoreNum: {
      type: Boolean,
      default: true
    },
    showEmpty: {
      type: Boolean,
      default: false
    },
    starStyle: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {
    showScore () {
      let scoreStr = this.score.toString()
      if (scoreStr.length < 2) {
        scoreStr = scoreStr + '.0'
      }
      return scoreStr
    },
    starCls () {
      let clsArr = []
      let starNum = this.score / 2
      for (let i = 1; i <= starNum; i++) {
        clsArr.push('onstar')
      }
      let halfStarNum = starNum % 1
      if (halfStarNum >= 0.5) {
        clsArr.push('halfstar')
      }
      for (let i = clsArr.length; i < 5; i++) {
        clsArr.push('offstar')
      }
      return clsArr
    }
  }
}
</script>

<style lang="stylus" scoped>
  .star-icon
    display: inline-block
    margin-right: .06rem
    width: .2rem
    height: .2rem
    background-size: .2rem .2rem
  .offstar
    background-image: url("")
  .onstar
    background-image: url("")
  .halfstar
    background-image: url("")
</style>
